<template>
  <div class>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="0">
        <el-col :span="8">
          <!-- 搜索区域 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="resetUsers">
            <el-button slot="append" icon="el-icon-search" @click="searchUsersResult"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addUsers">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户表格区域 -->
      <el-table :data="userList" style="width: 100%;margin-top:15px;" stripe border>
        <el-table-column prop="id" label="id" width="180"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column label="权限">
          <!-- 作用域插槽 可以拿到每一行的数据对象-->
          <template slot-scope="scope">
            <!-- 作用域插槽固定写法 -->
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUsers(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRolesDia(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- 
          current-page   当前页
          page-sizes     可选单页数据条数
          page-size     单页数据条数
          total         数据总条数
      -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mt15"
      ></el-pagination>
    </el-card>

    <!-- 新增用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserdialogVisible"
      width="30%"
      @close="resetAddUsersDia"
    >
      <!-- 表单区域 -->
      <el-form ref="addForm" :model="form" :rules="addUsersRules" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹窗 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserdialogVisible"
      width="30%"
      @close="resetEditUsersDia"
    >
      <!-- 表单区域 -->
      <el-form ref="editFormRef" :model="editform" :rules="editUsersRules" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesdialogVisible"
      width="30%"
      @close="resetSetRolesDia"
    >
      <!-- 用户信息以及角色列表 -->
      <div class="t-left">
        <p>用户名:{{userInfo.username}}</p>
        <p>用户当前角色:{{userInfo.role_name}}</p>
        <p>
          新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择角色">
            <!-- :label 显示文本，:value 选中值 -->
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSetRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    // 添加检测邮箱的方法
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error());
    };
    // 添加检测手机号的方法
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的手机号码"));
    };

    return {
      // 用户列表数据
      userList: [],
      // 用户列表数据参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      // 总共数据条数
      total: 0,
      // 添加用户窗口显示状态
      addUserdialogVisible: false,
      // 修改用户窗口显示状态
      editUserdialogVisible: false,
      // 添加用户表单数据
      form: {
        username: "",
        password: "",
        email: "",
        phone: "",
      },
      // 修改用户表单数据
      editform: {
        username: "",
        email: "",
        mobile: "",
        id: "",
      },
      // 添加用户数据的验证规则
      addUsersRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 自定义规则，可以用正则来进行对值的判断
          // validator这个方法对应的处理函数需要自定义
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // 自定义规则，可以用正则来进行对值的判断
          // validator这个方法对应的处理函数需要自定义
          {
            validator: checkMobile,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
      },
      // 修改用户数据的验证规则
      editUsersRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 自定义规则，可以用正则来进行对值的判断
          // validator这个方法对应的处理函数需要自定义
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // 自定义规则，可以用正则来进行对值的判断
          // validator这个方法对应的处理函数需要自定义
          {
            validator: checkMobile,
            message: "手机号格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
      },
      // 分配角色弹窗
      setRolesdialogVisible: false,
      // 存当前用户信息
      userInfo: {},
      // 存当前所有角色信息
      rolesList: [],
      // 分配角色下拉框中选中的选项的id
      selectedRoleId: null,
    };
  },
  created() {
    // 渲染时获取用户列表
    this.getUserList();
  },
  mounted() {},
  watch: {},
  computed: {},
  methods: {
    getUserList() {
      this.$axios.get("users", { params: this.queryInfo }).then((val) => {
        // console.log(val);
        if (val.meta.status != 200) {
          return this.$message.error("用户数据获取失败!");
        }
        this.userList = val.data.users;
        this.total = val.data.total;
      });
    },
    // 单页条数改变的处理事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      // 把改变的新的尺寸值赋值queryInfo里的pagesize
      this.queryInfo.pagesize = newSize;
      // 调用渲染用户列表的方法
      this.getUserList();
    },
    // 页码改变时的处理事件
    handleCurrentChange(newPageNum) {
      // console.log(newPageNum);
      this.queryInfo.pagenum = newPageNum;
      this.getUserList();
    },
    // 改变用户状态-权限的方法
    changeUserState(userInfo) {
      // console.log(userInfo);
      this.$axios
        .put("users/" + userInfo.id + "/state/" + userInfo.mg_state)
        .then((val) => {
          // console.log(val);
          if (val.meta.status != 200) {
            userInfo.mg_state = !userInfo.mg_state;
            return this.$message.error("修改状态失败!");
          }
          this.$message.success("修改状态成功!");
        });
    },
    // 搜索操作的结果
    searchUsersResult() {
      // 直接执行获取用户列表的方法
      this.getUserList();
    },
    // 清空搜索框时，执行重置用户列表
    resetUsers() {
      this.getUserList();
    },
    // 添加用户弹窗
    addUsers() {
      this.addUserdialogVisible = true;
    },
    // 关闭添加用户窗口的时候清空当前列表
    resetAddUsersDia() {
      this.$refs.addForm.resetFields();
    },
    // 关闭修改用户窗口的时候清空当前列表
    resetEditUsersDia() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击确定按钮添加用户事件
    submitUser() {
      this.$refs.addForm.validate((vai) => {
        console.log(vai);
        if (!vai) {
          return;
        }
        this.$axios.post("users", this.form).then((val) => {
          console.log(val);
          if (val.meta.status != 201) {
            return this.$message.error("添加用户失败!");
          }
          // 添加成功
          // 用户列表渲染
          this.getUserList();
          // 关闭窗口
          this.addUserdialogVisible = false;
          // 提示添加成功
          this.$message.success("添加用户成功!");
        });
      });
    },
    // 点击修改按钮打开修改的窗口
    editUsers(id) {
      this.editUserdialogVisible = true;
      this.$axios.get("/users/" + id).then((val) => {
        console.log(val);
        if (val.meta.status != 200) {
          return this.$message.error(val.meta.msg);
        }
        this.editform.username = val.data.username;
        this.editform.email = val.data.email;
        this.editform.mobile = val.data.mobile;
        this.editform.id = val.data.id;
      });
    },
    // 提交用户修改按钮处理事件
    submitEditUser() {
      this.$refs.editFormRef.validate((vai) => {
        // console.log(vai);
        if (!vai) {
          return;
        }
        // 调用接口发送修改请求
        this.$axios
          .put("users/" + this.editform.id, {
            email: this.editform.email,
            mobile: this.editform.mobile,
          })
          .then((val) => {
            // console.log(val);
            if (val.meta.status != 200) {
              return this.$message.error(val.meta.msg);
            }
            // 弹窗更改成功
            this.$message.success(val.meta.msg);
            // 对话框关掉
            this.editUserdialogVisible = false;
            // 重新渲染用户列表
            this.getUserList();
          });
      });
    },
    // 删除用户操作
    deleteUser(id) {
      // console.log(id);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 点击确定按钮才执行删除请求
          this.$axios.delete("/users/" + id).then((val) => {
            console.log(val);
            if (val.meta.status != 200) {
              return this.$message.error(val.meta.msg);
            }
            this.$message.success(val.meta.msg);
            // 重新渲染用户列表
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },
    // 点击分配角色按钮打开对话框
    showSetRolesDia(userInfo) {
      // 请求角色的数据
      this.$axios.get("roles").then((val) => {
        console.log(val);
        if (val.meta.status != 200) {
          return this.$message.error(val.meta.msg);
        }
        this.rolesList = val.data;
      });

      // console.log(userInfo);
      this.userInfo = userInfo;
      this.setRolesdialogVisible = true;
      // userInfo.id用户id
    },
    // 分配角色关闭窗口
    resetSetRolesDia() {
      this.selectedRoleId = null;
    },
    // 分配角色窗口确定按钮点击事件
    submitSetRoles() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择一个新角色!");
      }

      // 发请求分配新角色
      this.$axios
        .put("users/" + this.userInfo.id + "/role", {
          rid: this.selectedRoleId,
        })
        .then((val) => {
          console.log(val);
          if (val.meta.status != 200) {
            return this.$message.error(val.meta.msg);
          }
          this.getUserList();
          // 关闭对话框
          this.setRolesdialogVisible = false;
        });

      // this.userInfo.id用户id
    },
  },
};
</script>
<style lang="css" scoped>
.t-left {
  text-align: left;
}
</style>